/**
 * 将reducers组合中一个新的reducer，state树的结构和传入的reducers属性一样
 * @param {*} reducers 
 * @returns 
 */
export default function combineReducers(reducers) {
  // 判断reducers
  const keys = Object.keys(reducers);

  for (let i = 0, len = keys.length; i < len; i++) {
    if (typeof reducers[keys[i]] !== 'function') {
      throw new Error('Expected the reducer to be a function');
    }
  }

  // 返回新的reducer
  return function (state = {}, action) {
    const nextState = {};

    // 循环调用reducer，将返回的状态存储在一个大的状态中
    for (let i = 0, len = keys.length; i < len; i++) {
      const key = keys[i];
      const reducer = reducers[key];
      // 获取reducer对应key的状态
      const previousStateForKey = state[key];
      const nextStateForKey = reducer(previousStateForKey, action);
      // 将reducer的结果存储在nextState中
      nextState[key] = nextStateForKey;
    }

    return nextState;
  };
}